package com.bawei.module_goods.ui

import android.util.Log
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.mvi.base.BaseMVIActivity
import com.bawei.module_goods.adapter.GoodsAdapter
import com.bawei.module_goods.databinding.ActivityGoodsBinding
import com.bawei.module_goods.entity.EventsType
import com.bawei.module_goods.entity.GoodsBanner
import com.bawei.module_goods.entity.GoodsEntity
import com.bawei.module_goods.entity.GroupType
import com.bawei.module_goods.intent.GoodsIntent
import com.bawei.module_goods.section.GoodsSection
import com.bawei.module_goods.state.GoodsState
import com.bawei.module_goods.viewmodel.GoodsViewModel
import kotlinx.coroutines.launch

@Route(path = "/module_goods/GoodsActivity")
class GoodsActivity : BaseMVIActivity() {
    private lateinit var adapter: GoodsAdapter
    private lateinit var viewModel: GoodsViewModel
    private lateinit var binding : ActivityGoodsBinding

    private var bannerList: List<GoodsBanner> = emptyList()
    private var groupList: List<GroupType> = emptyList()
    private var eventList: List<EventsType> = emptyList()
    private var goodsList: List<GoodsEntity> = emptyList()

    private var isBannerLoaded = false
    private var isTabLoaded = false
    private var isEventLoaded = false
    private var isGoodsLoaded = false

    override fun generateViewModel() {
        viewModel = ViewModelProvider(this)[GoodsViewModel::class.java]
    }

    override fun initView() {
        super.initView()
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = GoodsAdapter()
        binding.recyclerView.adapter = adapter
        // 购物车图标跳转购物车页面
        binding.ivCart.setOnClickListener {
            com.alibaba.android.arouter.launcher.ARouter.getInstance()
                .build("/module_goods/ShoppingCartActivity")
                .navigation()
        }
        // 搜索栏点击跳转到搜索页面
        binding.layoutSearchBar.setOnClickListener {
            val intent = android.content.Intent(this, com.bawei.module_goods.ui.GoodsSearchActivity::class.java)
            startActivity(intent)
        }
    }
    
    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED){
                viewModel.intents.send(GoodsIntent.LoadHomeData)
            }
        }
    }

    override fun handleState() {
        // 监听数据流并刷新UI
        lifecycleScope.launch {
            repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED) {
                viewModel.mallHomeStateFlow.collect { state ->
                    when (state) {
                        GoodsState.Empty -> {
                            // 可显示空页面
                        }
                        GoodsState.Init -> {
                            // 初始状态，无需处理
                        }
                        is GoodsState.onFailed -> {
                            Log.e("GoodsActivity", "onFailed: ${state.msg}")
                        }
                        is GoodsState.onSuccess -> {
                            when (state.type) {
                                "banner" -> {
                                    bannerList = state.data as? List<GoodsBanner> ?: emptyList()
                                    isBannerLoaded = true
                                }
                                "group" -> {
                                    groupList = state.data as? List<GroupType> ?: emptyList()
                                    isTabLoaded = true
                                }
                                "event" -> {
                                    eventList = state.data as? List<EventsType> ?: emptyList()
                                    isEventLoaded = true
                                }
                                "goods" -> {
                                    goodsList = state.data as? List<GoodsEntity> ?: emptyList()
                                    isGoodsLoaded = true
                                }
                            }
                            // 只在三种数据都加载完毕后赋值一次
                            if (isBannerLoaded && isTabLoaded && isEventLoaded) {
                                val sections = mutableListOf<GoodsSection>()
                                if (groupList.isNotEmpty()) {
                                    sections.add(GoodsSection.Tab(groupList))
                                }
                                if (bannerList.isNotEmpty()) {
                                    sections.add(GoodsSection.Banner(bannerList))
                                }
                                if (eventList.isNotEmpty()) {
                                    sections.add(GoodsSection.Event(eventList))
                                }
                                if (goodsList.isNotEmpty()) {
                                    sections.add(GoodsSection.Goods(goodsList))
                                }
                                adapter.dataList = sections
                            }
                        }
                    }
                }
            }
        }
    }

    override fun getLayoutRootView() : View{
        binding = ActivityGoodsBinding.inflate(layoutInflater)
        return binding.root
    }
}